"""this script parse the content of a xml file"""
import select
import socket
from time import sleep


class NetThread():
    """ Summary of class here.
    网口线程
    """

    def __init__(self):
        super(NetThread, self).__init__()
        self.net_port = 28090
        self.socket = None
        self.net_cfg_flag = True
        self.connect_count = 0
        self.socket_obj = []

    def __save_data(self, data):
        """
        将数据存放到指定的文件中
        :param : None
        :return: True or false
        """
        try:
            file_handle = open('output.txt', 'a')
            file_handle.write(str(data) + "\n")
            file_handle.close()
        except Exception as e:
            print("save err")
            return False

    def __net_cfg(self):
        """
        对网口的参数进行配置
        :param : 略
        :return: True or false
        """
        self.socket = socket.socket()
        ser_addr = ("", self.net_port)
        try:
            self.socket.bind(ser_addr)
            self.socket.listen(5)
            self.socket.setblocking(False)
            print("打开监听端口成功")
        except:
            #一般是由于端口号异常导致的
            self.socket.close()
            return False
        return True

    def run(self):
        """
        网口检测客户端连接
        """
        while True:
            sleep(0.01)
            self.connect_count = self.connect_count + 1
            if self.net_cfg_flag is True:
                if self.__net_cfg() is False:
                    continue
                self.net_cfg_flag = False
                my_inp = [
                    self.socket,
                ]
            #监听my_inp列表中的元素是否被触动
            r, w, e = select.select(my_inp, [], [])
            for obj in r:
                if obj == self.socket:
                    conn, addr = obj.accept()
                    #conn连接时，把它添加到监听列表中
                    my_inp.append(conn)
                    self.__save_data(addr)
                    print(addr)
                else:
                    try:
                        data = obj.recv(1024)
                    except:
                        continue
                    if data:
                        print(data)
                        self.__save_data(data)
                        obj.sendall(b'11')
                """ #每隔10秒断一次
                if (self.connect_count >= 10):
                    self.connect_count = 0
                    my_inp.remove(obj)
                    obj.close()
                    self.__save_data("close")
                    print("close") """


if __name__ == '__main__':
    APP = NetThread()
    APP.run()
    sys.exit(APP.exec_())
